package com.onetwork.core.model;

import java.util.ArrayList;
import java.util.List;
import javax.swing.table.DefaultTableModel;

public abstract class CoreTableModel<T> extends DefaultTableModel {
    private String[] columnNames;
    private static final long serialVersionUID = 1L;
    protected List<T> objects;
    
    public CoreTableModel(String[] columnNames) {
        this.columnNames = columnNames;
        this.objects = new ArrayList<T>();
    }
    
    public void addObject(T object) {
        this.objects.add(object);
    }

    public void addObjects(List<T> objects) {
        this.objects = objects;
    }

    public void clear() {
        this.objects.clear();
    }

    public T getObjectSelected(int index) {
        return this.objects.get(index);
    }
    
    public List<T> getObjectsSelecionados(int[] rows) {
        List<T> objectsSelecionados = new ArrayList<T>();
        T[] arrayObjects = (T[])objects.toArray();
        for (int i = 0; i < rows.length; i++) objectsSelecionados.add(arrayObjects[rows[i]]);
        return objectsSelecionados;
    }

    public void removeObject(T object) {
        this.objects.remove(object);
    }

    @Override
    public void removeRow(int row) {
        if (row > -1 && row < this.objects.size()) this.objects.remove(this.objects.toArray()[row]);
    }
    
    @Override
    public int getColumnCount() {
        return columnNames.length;
    }

    public List<T> getObjects() {
        return this.objects;
    }
    
    @Override
    public int getRowCount() {
        return this.objects != null ? this.objects.size() : 0;
    }

    @Override
    public String getColumnName(int col) {
        return columnNames[col];
    }
}
